﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Management.Automation;
using Microsoft.Hpc.Scheduler;
using System.Xml;

namespace pshcli
{
    //static calls
    public class PshLib
    {
        //public static bool CheckFile(string file)
        //{
        //    bool isUsed = false;
        //    FileStream ft = null;

        //    try
        //    {
        //        ft = File.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        //    }
        //    catch (System.IO.FileNotFoundException)
        //    {
        //        isUsed = false;
        //    }
        //    catch (IOException)
        //    {
        //        Console.WriteLine("DWARF-ERROR: An error occured when accessing the following file: " + file);
        //        //Console.WriteLine("         " + e.Message);
        //        isUsed = true;
        //    }

        //    if (ft != null)
        //    {
        //        ft.Close();
        //        ft.Dispose();
        //    }
        //    return isUsed;
        //}
    }


    public class Log
    {
        TextWriter logwriter;
        bool enabled;
        public string lfile;

        public Log(string logfilename)
        {
            this.lfile = logfilename;
            if (File.Exists(logfilename))
                File.Delete(logfilename);

            FileStream logfile;

            try
            {
                logfile = new FileStream(logfilename, FileMode.Append);
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR: Cannot create log file: " + e.Message);
                Console.WriteLine("       Logging to file will be disabled.");
                enabled = false;
                return;
            }

            logwriter = new StreamWriter(logfile);
            enabled = true;
        }

        public void Close()
        {
            if (enabled)
            {
                logwriter.WriteLine("LOG[LOG]: Closed.");
                logwriter.Flush();
                logwriter.Close();
            }
        }

        public void WriteLog(string component, string logmsg)
        {
            if (enabled)
            {
                try
                {
                    Monitor.Enter(logwriter);
                    logwriter.WriteLine("LOG[" + component + "]: " + logmsg);
                    logwriter.Flush();
                    Monitor.Exit(logwriter);
                }
                catch (Exception exp)
                {
                    throw new Exception("ERROR: Log exception: " + exp.Message.ToString());
                }
            }
        }
    }





}
